from flask import Flask, render_template, jsonify, request
import json
import os
from datetime import datetime
import threading
import time

app = Flask(__name__)

# 全局变量存储分析结果
analysis_data = {
    'alerts': [],
    'statistics': {},
    'protocols': {},
    'detection_summary': {},
    'last_update': None,
    'bandwidth_stats': [],
    'top_hosts': []
}

def load_analysis_results():
    """加载分析结果"""
    global analysis_data
    try:
        if os.path.exists('analysis_results.json'):
            with open('analysis_results.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
                analysis_data.update(data)
                analysis_data['last_update'] = datetime.now().isoformat()
    except Exception as e:
        print(f"加载分析结果错误: {e}")

@app.route('/')
def index():
    """主页面"""
    return render_template('dashboard.html')

@app.route('/api/statistics')
def get_statistics():
    """获取统计信息"""
    return jsonify(analysis_data.get('statistics', {}))

@app.route('/api/alerts')
def get_alerts():
    """获取告警信息"""
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    
    alerts = analysis_data.get('alerts', [])
    total = len(alerts)
    
    # 分页
    start = (page - 1) * per_page
    end = start + per_page
    paginated_alerts = alerts[start:end]
    
    return jsonify({
        'alerts': paginated_alerts,
        'total': total,
        'page': page,
        'per_page': per_page,
        'pages': (total + per_page - 1) // per_page
    })

@app.route('/api/protocols')
def get_protocols():
    """获取协议统计"""
    return jsonify(analysis_data.get('protocols', {}))

@app.route('/api/detection_summary')
def get_detection_summary():
    """获取检测类型统计"""
    return jsonify(analysis_data.get('detection_summary', {}))

@app.route('/api/bandwidth')
def get_bandwidth():
    """获取带宽统计"""
    return jsonify(analysis_data.get('bandwidth_stats', []))

@app.route('/api/top_hosts')
def get_top_hosts():
    """获取Top N通信主机"""
    return jsonify(analysis_data.get('top_hosts', []))

@app.route('/api/refresh')
def refresh_data():
    """刷新数据"""
    load_analysis_results()
    return jsonify({'status': 'success', 'last_update': analysis_data['last_update']})

@app.route('/api/alert_details/<int:alert_id>')
def get_alert_details(alert_id):
    """获取告警详情"""
    alerts = analysis_data.get('alerts', [])
    if 0 <= alert_id < len(alerts):
        return jsonify(alerts[alert_id])
    return jsonify({'error': '告警不存在'}), 404

@app.route('/api/summary')
def get_summary():
    """获取总体摘要"""
    return jsonify({
        'statistics': analysis_data.get('statistics', {}),
        'protocols': analysis_data.get('protocols', {}),
        'detection_summary': analysis_data.get('detection_summary', {}),
        'total_alerts': len(analysis_data.get('alerts', [])),
        'last_update': analysis_data.get('last_update')
    })

if __name__ == '__main__':
    # 初始加载数据
    load_analysis_results()
    
    # 启动Web服务器
    app.run(debug=True, host='0.0.0.0', port=5000) 